﻿package dut.ir.lxb.weibo.io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import dut.ir.lxb.weibo.bean.WeiboBean;
import dut.ir.lxb.weibo.util.SpiderConfig;

public class WeiboInfoWriter extends WeiboWriter
{
	
	protected OutputStream os;

	public WeiboInfoWriter(String file)
	{
		super(file);
		try
		{
			os = new FileOutputStream(file);
		} 
		catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public WeiboInfoWriter()
	{
		
	}
	
	@SuppressWarnings({ "rawtypes", "static-access" })
	@Override
	public boolean writeHeader(Class headerClass)
	{
		try
		{
			WeiboBean wb = (WeiboBean)headerClass.newInstance();
			byte[] outBytes = (wb.getHeader() + "\n").getBytes(SpiderConfig.getOutputEncoding());
			os.write(outBytes);
			os.flush();
		} 
		catch(IOException e)
		{
			e.printStackTrace();
		}
		catch (InstantiationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean writeBody(Object bodyObject)
	{
		byte[] outBytes;
		try
		{
			outBytes = (bodyObject.toString() + "\n").getBytes(SpiderConfig.getOutputEncoding());
			os.write(outBytes);
			os.flush();
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void close()
	{
		try
		{
			os.close();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		
	}
	
}
